using Microsoft.AspNetCore.Mvc;
using ProduceBasicData.Api.Services;
using ProduceBasicData.ErrorCode;

namespace ProduceBasicData.Api.Controllers
{
    /// <summary>
    /// AI聊天控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AIChatController : ControllerBase
    {
        private readonly IAIService _aiService;
        private readonly ILogger<AIChatController> _logger;

        public AIChatController(
            IAIService aiService,
            ILogger<AIChatController> logger)
        {
            _aiService = aiService;
            _logger = logger;
        }

        /// <summary>
        /// 发送聊天消息
        /// </summary>
        /// <param name="request">聊天请求</param>
        /// <returns>AI回复</returns>
        [HttpPost("send")]
        public async Task<ActionResult<ApiResult<string>>> SendMessage([FromBody] ChatRequest request)
        {
            try
            {
                if (string.IsNullOrEmpty(request.Message))
                {
                    return BadRequest(new ApiResult<string>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "消息内容不能为空"
                    });
                }

                var reply = await _aiService.SendMessageAsync(
                    request.Message, 
                    request.Context, 
                    request.Model);

                return Ok(new ApiResult<string>
                {
                    Code = ApiEnum.Success,
                    Msg = "消息发送成功",
                    Data = reply
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送聊天消息时发生错误");
                return StatusCode(500, new ApiResult<string>
                {
                    Code = ApiEnum.Failed,
                    Msg = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 生成智能回复
        /// </summary>
        /// <param name="request">生成请求</param>
        /// <returns>AI回复</returns>
        [HttpPost("generate")]
        public async Task<ActionResult<ApiResult<string>>> GenerateReply([FromBody] GenerateRequest request)
        {
            try
            {
                if (string.IsNullOrEmpty(request.Message))
                {
                    return BadRequest(new ApiResult<string>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "消息内容不能为空"
                    });
                }

                var reply = await _aiService.GenerateReplyAsync(
                    request.Message, 
                    request.SystemPrompt, 
                    request.Model);

                return Ok(new ApiResult<string>
                {
                    Code = ApiEnum.Success,
                    Msg = "回复生成成功",
                    Data = reply
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成AI回复时发生错误");
                return StatusCode(500, new ApiResult<string>
                {
                    Code = ApiEnum.Failed,
                    Msg = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 分析文本内容
        /// </summary>
        /// <param name="request">分析请求</param>
        /// <returns>分析结果</returns>
        [HttpPost("analyze")]
        public async Task<ActionResult<ApiResult<string>>> AnalyzeText([FromBody] AnalyzeRequest request)
        {
            try
            {
                if (string.IsNullOrEmpty(request.Text))
                {
                    return BadRequest(new ApiResult<string>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "文本内容不能为空"
                    });
                }

                var result = await _aiService.AnalyzeTextAsync(
                    request.Text, 
                    request.AnalysisType ?? "summary");

                return Ok(new ApiResult<string>
                {
                    Code = ApiEnum.Success,
                    Msg = "文本分析成功",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析文本时发生错误");
                return StatusCode(500, new ApiResult<string>
                {
                    Code = ApiEnum.Failed,
                    Msg = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 健康检查
        /// </summary>
        /// <returns>服务状态</returns>
        [HttpGet("health")]
        public ActionResult<ApiResult<object>> HealthCheck()
        {
            return Ok(new ApiResult<object>
            {
                Code = ApiEnum.Success,
                Msg = "AI服务运行正常",
                Data = new { Status = "Healthy", Timestamp = DateTime.Now }
            });
        }
    }

    /// <summary>
    /// 聊天请求
    /// </summary>
    public class ChatRequest
    {
        /// <summary>
        /// 用户消息
        /// </summary>
        public string Message { get; set; } = string.Empty;

        /// <summary>
        /// 上下文信息
        /// </summary>
        public string? Context { get; set; }

        /// <summary>
        /// AI模型（可选，默认使用配置文件中的模型）
        /// </summary>
        public string? Model { get; set; }
    }

    /// <summary>
    /// 生成请求
    /// </summary>
    public class GenerateRequest
    {
        /// <summary>
        /// 用户消息
        /// </summary>
        public string Message { get; set; } = string.Empty;

        /// <summary>
        /// 系统提示词
        /// </summary>
        public string? SystemPrompt { get; set; }

        /// <summary>
        /// AI模型（可选，默认使用配置文件中的模型）
        /// </summary>
        public string? Model { get; set; }
    }

    /// <summary>
    /// 分析请求
    /// </summary>
    public class AnalyzeRequest
    {
        /// <summary>
        /// 要分析的文本
        /// </summary>
        public string Text { get; set; } = string.Empty;

        /// <summary>
        /// 分析类型
        /// </summary>
        public string? AnalysisType { get; set; } = "summary";
    }
}
